package com.ybwh.springboot1.controller;

import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.ybwh.springboot1.common.Constant;
import com.ybwh.springboot1.common.Response;
import com.ybwh.springboot1.dao.DictDao;
import com.ybwh.springboot1.model.po.Dict;

@RestController
@RequestMapping("/")
public class DictController implements ApplicationContextAware {
	private ApplicationContext applicationContext;

	@Value("${spring.datasource.url}")
	private String dataSourceUrl;

	@Autowired
	private DictDao dictDao;

	@RequestMapping("/index")
	public ModelAndView test() {

		ModelAndView mv = new ModelAndView("index");
		mv.addObject("dataSourceUrl", dataSourceUrl);
		return mv;

	}

	@RequestMapping(value = "/getDict")
	@ResponseBody
	public Response<List<Dict>> getDict(@RequestParam("group") String group) {

		String sql = "select * from dict where dict_group=?";
		List<Dict> list = dictDao.query(sql, new Object[] { group }, Dict.class);
		if (CollectionUtils.isEmpty(list)) {
			return new Response<>(Constant.FAIL_CODE, " test response", null);
		}

		return new Response<>(Constant.SUCCEED_CODE, null, list);

	}

	@RequestMapping(value = "/refreshBean")
	@ResponseBody
	public Response<Object> refreshBean(@RequestParam("group") String group) {

		if (applicationContext instanceof ConfigurableApplicationContext) {
			((ConfigurableApplicationContext) applicationContext).refresh();

			return new Response<>(Constant.SUCCEED_CODE);
		} else {
			return new Response<>(Constant.FAIL_CODE);
		}

	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

}
